package persistencia;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import com.thoughtworks.xstream.XStream;

/**
 * Clase que encapsula la serializacion y conversion a xml con xstream y el
 * manejo de archivos.
 * 
 * @author ari
 * 
 */
public class XMLUtils {

	public XMLUtils() {
	}

	public static String getXML(Object object) {
		XStream xstream = new XStream();
		return xstream.toXML(object);
	}

	public static Object objectFromXMLString(String xml) {
		XStream xstream = new XStream();
		return xstream.fromXML(xml);
	}

	public static Object objectFromXMLFile(String path) throws IOException {
		String xmlString = null;
		FileInputStream stream = new FileInputStream(new File(path));
		try {
			FileChannel fc = stream.getChannel();
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
					fc.size());
			/* Instead of using default, pass in a decoder. */
			xmlString = Charset.defaultCharset().decode(bb).toString();
			return XMLUtils.objectFromXMLString(xmlString);
		} finally {
			stream.close();
		}

	}

}
